

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';

///如果页面比较复杂，如外部有intrinsicHeight之类的控件，会报错，所以V2这个版本@AutoGridWidgetV2
class AutoGridWidget extends StatelessWidget {

  final int rowNum;
  final int colNum;
  final Widget? moreView;
  final double padding;
  final List<Widget> widgets;
  final double radius;

  const AutoGridWidget({
    Key? key,
    this.rowNum = 1,
    this.colNum = 2,
    this.moreView,
    this.padding = 3,
    this.widgets = const [],
    this.radius = 0
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          print('constraints.maxWidth  ${constraints.maxWidth} height ${constraints.maxHeight}');
          double width = constraints.maxWidth;
          double gridSize = (width - (colNum - 1) * padding) / colNum;
          int num = moreView == null ? colNum : colNum - 1;
          List<Widget> widgetList = widgets;
          if (num < widgets.length) {
            widgetList = widgets.sublist(0, num);
          }
          if (moreView != null) widgetList.add(moreView!);
          for (int i = widgetList.length; i < colNum; i++) {
            widgetList.add(W(0));
          }
          List<Widget> result = widgetList.map((e) {
            // if (e == null) return SizedBox(width: gridSize, height: gridSize, child: Text(''),);
            return RoundedCornerWidget(borderColor: Colors.transparent, borderWidth: 0, radius: radius, child: e, width: gridSize, height: gridSize,);
          }).toList();

          return Row(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            ...result
          ]);
        });
    }

}

class AutoGridImage extends StatelessWidget {
  final int rowNum;
  final int colNum;
  final Widget? moreView;
  final double padding;
  final List<String?> imageUrls;
  final double radius;

  const AutoGridImage({
    Key? key,
    this.rowNum = 1,
    this.colNum = 2,
    this.moreView,
    this.padding = 3,
    this.imageUrls = const [],
    this.radius = 0
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> list = imageUrls.map((e) {
      if (e?.isNotEmpty == true) {
        return LoadImage(e!);
      } else {
        return W(0);
      }
    }).toList();
    return AutoGridWidget(rowNum: rowNum, colNum: colNum, moreView: moreView, padding: padding, widgets: list, radius: radius,);
  }


}